<?php

namespace Admin\Frontend\Controllers;

use Exception;
use Helpers\Main;
use Helpers\Template;
use Helpers\Assets;
use Helpers\UserPower;
use Helpers\XhException;
use Modules\School;
use Services\MicroServer;

class ServerConfigController extends ControllerBase
{
    /**
     * 微服务配置列表页面
     *
     * create by fyh 20181129
     */
    public function serverConfigListAction()
    {
        $this->view->pick('server_config/serverConfigList');
        $this->assets->addJs('assets/jquery/jquery.form.js');
        Assets::select2();
        Assets::easyUI('js/server_config/serverConfigList.js');
        Main::showNavPosition();
        if (!UserPower::checkUserPower('ServerConfig_ServerConfigList_App')) {
            return $this->sendViewError('无查看权限');
        }
        $listButtonArr = $listSearchArr = $formButtonArr = [];
        $listSearchArr[] = [
            'type' => 'select',
            'id' => 'List_Search_status',
            'style' => 'width: 75px;',
            'data' => [0 => '--状态--',
                1 => '正常' ,
                2 => '下线'
            ]
        ];
        $listSearchArr[] = ['type'=>'text', 'id'=>'List_Search_keyword', 'label'=>' 搜索：'];
        if (UserPower::checkUserPower('ServerConfig_ServerConfigList_App_Add')) {
            $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus'];
            $formButtonArr[] = ['id' => 'bt_form_add', 'text' => '保存'];
        }
        if (UserPower::checkUserPower('ServerConfig_ServerConfigList_App_Edit')) {
            $formButtonArr[] = ['id' => 'bt_form_edit', 'text' => '保存'];
        }
        if (UserPower::checkUserPower('ServerConfig_ServerConfigList_App_Del')) {
            $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash'];
        }
        $formButtonArr[] = ['id'=>'bt_form_back', 'text'=>'返回'];
        $formButtonArr[] = ['id'=>'bt_form_reset', 'text'=>'重置'];
        $schoolList['schoolId'] = School::getSchools();
        return $this->view->setVars([
            'List'          => Template::createList('List', 'XHServer_Config', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'Form'          => Template::createForm('XHServer_Config', $schoolList),
            'FormButton'    => Template::createButtonToolBar($formButtonArr),
        ]);
    }

    /**
     * 获取微服务配置列表数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by fyh 20181129
     */
    public function getMicroServerConfigDataAction()
    {
        try {
            $serverType = $this->request->getPost('serverType', 'string');
            $keyword = $this->request->getPost('keyword', 'string');
            $enabled= $this->request->getPost('enabled', 'string');
            $status = $this->request->getPost('status', 'int');
            $page = $this->request->getPost('page', 'int', 1);
            $size = $this->request->getPost('rows', 'int', 25);
            $search = [];
            if ($keyword) {
                $search['keyword'] = $keyword;
            }
            if ($enabled) {
                $search['keyword'] = $enabled;
            }
            if ($status == 1) {
                $search['enabled'] = true;
            } elseif ($status == 2) {
                $search['enabled'] = false;
            }
            $result = MicroServer::getConfigData($page, $size, $search, $serverType);
            return $this->sendJsonResponse($result);
        } catch (Exception $e) {
            return $this->sendErrorResponse(400, json_encode($serverType));
        }
    }

    /**
     * 获取一条微服务配置数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by fyh 20181129
     */
    public function getMicroServerConfigOneAction()
    {
        try {
            $id = $this->request->getPost('id', 'string');
            $type = $this->request->getPost('type', 'string');
            $result = MicroServer::getConfigOne($id, $type);
            return $this->sendJsonResponse($result);
        } catch (Exception $e) {
            return $this->sendErrorResponse(400, $e->getMessage());
        }
    }

    /**
     * 注册服务
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws XhException
     *
     * create by fyh 20181129
     */
    public function registerMicroServerConfigAction()
    {
        $type = $this->request->getPost('type');
        if (!$type || !in_array($type, ['APP', 'ACCESS', 'SCHOOL'])) {
            return $this->sendErrorResponse(400, '类型错误');
        }
        switch ($type) {
            case 'APP':
                $power = 'ServerConfig_ServerConfigList_App_Add';
                break;
            case 'ACCESS':
                $power = 'ServerConfig_ServerConfigList_Access_Add';
                break;
            default:
                $power = 'ServerConfig_ServerConfigList_School_Add';
                break;
        }
        if (!UserPower::checkUserPower($power)) {
            return $this->sendErrorResponse(400, '无权限操作');
        };
        $data = $this->request->getPost();
        if ($data['type'] == 'SCHOOL') {
            unset($data['serverType']);
            unset($data['tactic']);
            unset($data['addressReturnType']);
        } elseif ($data['type'] == 'APP') {
            unset($data['customType']);
            unset($data['serverId']);
            unset($data['schoolId']);
        } else {
            unset($data['customType']);
            unset($data['serverId']);
            unset($data['serverType']);
        }
        if (empty($data['order'])) {
            $data['order'] = 0;
        }
        if (!empty($data['customType'])) {
            $data['customConfigRequests'] = [];
            for ($i = 0; $i < count($data['customType']); $i++) {
                if (!empty($data['customType'][$i])) {
                    $arr = [
                        'customType' =>$data['customType'][$i],
                        'serverId' =>$data['serverId'][$i],
                    ];
                    array_push($data['customConfigRequests'], $arr);
                }
            }
            unset($data['customType']);
            unset($data['serverId']);
        }
        try {
            MicroServer::registerConfig($data);
            return $this->sendSuccessResponse('注册成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 更新服务
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws XhException
     *
     * create by fyh 20181129
     */
    public function updateMicroServerConfigAction()
    {
        $type = $this->request->getPost('type');
        if (!$type || !in_array($type, ['APP', 'ACCESS', 'SCHOOL'])) {
            return $this->sendErrorResponse(400, '类型错误');
        }
        switch ($type) {
            case 'APP':
                $power = 'ServerConfig_ServerConfigList_App_Edit';
                break;
            case 'ACCESS':
                $power = 'ServerConfig_ServerConfigList_Access_Edit';
                break;
            default:
                $power = 'ServerConfig_ServerConfigList_School_Edit';
                break;
        }
        if (!UserPower::checkUserPower($power)) {
            return $this->sendErrorResponse(400, '无权限操作');
        };
        $data = $this->request->getPost();
        if (empty($data['type'])) {
            return $this->sendErrorResponse(400, '配置类型为空');
        }
        if (!empty($data['customType'])) {
            $data['customConfigRequests'] = [];
            for ($i = 0; $i < count($data['customType']); $i++) {
                if (!empty($data['customType'][$i])) {
                    $arr = [
                        'customType' =>$data['customType'][$i],
                        'serverId' =>$data['serverId'][$i],
                    ];
                    array_push($data['customConfigRequests'], $arr);
                }
            }
            unset($data['customType']);
            unset($data['serverId']);
        }
        $serverId = $data['id'];
        try {
            MicroServer::updateConfig($serverId, $data);
            return $this->sendSuccessResponse('更新成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 停用服务
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by fyh 20181129
     */
//    public function stopMicroServerConfigAction()
//    {
//        if (!UserPower::checkUserPower('ServerConfig_ServerConfigList_Edit')) {
//            return $this->sendErrorResponse(400, '无权限操作');
//        };
//        $serverIds = $this->request->getPost('ids', 'string');
//        if (!$serverIds) {
//            return $this->sendErrorResponse(400, '缺少id');
//        }
//        try {
//            MicroServer::stopConfig($serverIds[0]);
//            return $this->sendSuccessResponse('成功停止');
//        } catch (XhException $e) {
//            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
//        }
//    }

    /**
     * 启用服务
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by fyh 20181129
     */
//    public function startMicroServerConfigAction()
//    {
//        if (!UserPower::checkUserPower('ServerConfig_ServerConfigList_Edit')) {
//            return $this->sendErrorResponse(400, '无权限操作');
//        };
//        $serverIds = $this->request->getPost('ids');
//        if (!$serverIds) {
//            return $this->sendErrorResponse(400, '缺少id');
//        }
//        try {
//            MicroServer::startConfig($serverIds[0]);
//            return $this->sendSuccessResponse('启用成功');
//        } catch (XhException $e) {
//            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
//        }
//    }

    /**
     * 删除服务
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by fyh 20181129
     */
    public function deleteMicroServerConfigAction()
    {
        $type = $this->request->getPost('type');
        if (!$type || !in_array($type, ['APP', 'ACCESS', 'SCHOOL'])) {
            return $this->sendErrorResponse(400, '类型错误');
        }
        switch ($type) {
            case 'APP':
                $power = 'ServerConfig_ServerConfigList_App_Del';
                break;
            case 'ACCESS':
                $power = 'ServerConfig_ServerConfigList_Access_Del';
                break;
            default:
                $power = 'ServerConfig_ServerConfigList_School_Del';
                break;
        }
        if (!UserPower::checkUserPower($power)) {
            return $this->sendErrorResponse(400, '无权限操作');
        };
        $serverIds = $this->request->getPost('ids');
        if (!$serverIds) {
            return $this->sendErrorResponse(400, '缺少id');
        }
        try {
            MicroServer::deleteConfig($serverIds[0]);
            return $this->sendSuccessResponse('删除成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }


}

